<template>
  <div class="container">
    <list
        class="withdraw-list-container"
        @scroll="onPageScroll">
      <page-refresh v-on:refresh="onXRefresh" v-on:pullingDown="onPullingDown" :refreshing="refreshing"
                    :indicatorScale="indicatorScale"></page-refresh>
      <header>
        <navbar title="我的钱包" theme="gradient" rightItemText="提现" @rightItemClick="rightItemClick"></navbar>
      </header>
      <cell>
        <div class="balance-box" ref="top">
          <text class="balance-val">{{money}}</text>
        </div>
      </cell>
      <cell v-for="(flow) in walletFlowDetailList" v-bind:key="flow.id">
        <div class="wallet-flow" @click="showDetail(flow)">
          <div class="flow-detail">
            <text class="flow-title">{{flow.typeTitle}}</text>
            <text class="flow-time">{{flow.createTime}}</text>
          </div>
          <div class="flow-right">
            <text :class="['flow-val', flow.value > 0 && 'flow-val-income']">{{flow.value > 0 ? '+ ' + flow.value.toFixed(2) : '- ' + (-flow.value.toFixed(2))}}</text>
            <text :class="['flow-status', checkStatusStyle(flow)]" v-if="flow.status">{{flow.statusTitle}}</text>
          </div>
        </div>
      </cell>
      <cell>
        <page-notice msg="抱歉，什么都木有找到～" v-if="walletFlowDetailList.length === 0  && !hasNext"></page-notice>
      </cell>
      <page-loading-more v-on:loadingMore="onLoadingMore" :loadingMore="loadingMore"
                         :shown="hasNext"></page-loading-more>
    </list>
    <wxc-mask width="702"
              height="720"
              border-radius="10"
              duration="200"
              mask-bg-color="#FFFFFF"
              :has-animation="true"
              :has-overlay="true"
              :show-close="true"
              @wxcMaskSetHidden="withdrawPanelHidden"
              :show="withdrawPanelShow">
      <div class="withdraw-panel">
        <div class="form-row">
          <text class="form-row-icon icon">&#xe7d1;</text>
          <xinput :placeholder="'请输入提现金额,最多' + parseInt(money) +'元'"
                  :value.sync="withdrawParams.money" type="number" class="form-row-control"></xinput>
        </div>
        <div class="form-row">
          <text class="form-row-icon icon">&#xe769;</text>
          <xinput placeholder="请输入手机验证码" type="number" maxLength="6" :value.sync="withdrawParams.verifyCode"
                  class="form-row-control"></xinput>
          <text class="form-row-btn activeable" @click="sendMsg">{{cooldown ? '剩余' + cooldown + 's' : '获取验证码'}}</text>
        </div>
        <div class="form-row">
          <text class="form-row-icon icon">&#xe604;</text>
          <xinput placeholder="请输入支付宝账号" type="text" :value.sync="withdrawParams.payeeAccount"
                  class="form-row-control"></xinput>
        </div>
        <div class="form-row">
          <text class="form-row-icon icon">&#xe62b;</text>
          <xinput placeholder="支付宝收款人姓名" type="text" :value.sync="withdrawParams.payeeName"
                  class="form-row-control"></xinput>
        </div>
        <text class="withdraw-panel-tip">申请提现后，3-5个工作日到账，请耐心等待！</text>
        <text :class="['btn-primary','btn', 'activeable','btn-large', validateOk || 'btn-disabled']" @click="applyWithdraw">申请提现</text>
      </div>
    </wxc-mask>
    <page-scrolltop :shown="pageScrollTopShown" @click="gotoTop"></page-scrolltop>
    <wxc-loading :show="loadingShow"></wxc-loading>
  </div>
</template>
<style lang="scss">
  @import "./sass/var";
  @import "./sass/mixin";
  @import "./sass/utilities";
  @import "./sass/icon";
  @import "./sass/buttons";
  @import "./sass/form";
  @import "./sass/activeable";
  .container{
    background-color: $body-bg;
    transition: transform .3s linear
  }

  .balance-box {
    height: 200px;
    flex-direction: row;
    background-image: $gradient-bg-primary;
    justify-content: center;
    padding-top: 20px;
    &-info {
      &-title {
        color: #FFFFFF;
        font-size: 24px;
        margin-bottom: 10px;
      }
      &-val {

      }
    }
  }

  .withdraw-panel {
    padding: 40px;
    &-tip {
      color: $color-muted;
      font-size: 24px;
      padding: 0px 0 30px;
      text-align: center;
    }
  }

  .filterbar {
    flex-direction: row;
    justify-content: space-between;
    &-item {
      text-align: center;
      height: 80px;
      background-color: #FFFFFF;
      line-height: 80px;
      color: $color;
      font-size: 32px;
      @include border-bottom(1, solid, #ddd);
      flex: 1;
      &-current {
        color: $color-primary;
        @include border-bottom(1, solid, $brand-primary);
      }
    }
  }

  .balance-val {
    font-size: 100px;
    font-weight: 100;
    color: #ffe500;
  }
  .wallet-flow {
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    background-color: #FFFFFF;
    @include border-bottom(1, solid, #ddd);
  }
  .flow {
    &-detail {

    }
    &-right {
      align-items: flex-end;
    }
    &-status {
      font-size: 24px;
    }
    &-title {
      color: $color;
      font-size: 30px;
      margin-bottom: 5px;
      font-weight: 300;
    }
    &-time {
      font-size: 28px;
      color: $color-muted;
      font-weight: 300;
    }
    &-val {
      font-size: 50px;
      color: $color-primary;
      font-weight: 300;
      &-income {
        color: $color-success;
      }
    }
  }
</style>
<script>

import { WxcRichText, WxcMask, WxcLoading } from 'weex-ui'
let api = require('./include/api')
let Deferred = require('Deferred')
require('./include/page-xdom')
let queryParser = require('./include/queryparser')
let modal = weex.requireModule('modal')
let navigator = require('./include/xnavigator')
let DEFAULT_SEARCH_PARAM = {
  page: 1,
  valueType: 'MONEY'
}
module.exports = {
  mixins: [
    require('./mixin/page-refresh'),
    require('./mixin/page-loading-more'),
    require('./mixin/page-scrolltop')
  ],
  components: {
    'page-notice': require('./components/page-notice.vue'),
    navbar: require('./components/navbar.vue'),
    WxcRichText,
    WxcMask,
    xinput: require('./components/input.vue'),
    WxcLoading
  },
  data () {
    return {
      money: 0,
      withdrawPanelShow: false,
      withdrawDoing: false,
      validateOk: false,
      loadingShow: false,
      minWithdrawValue: 10000,
      withdrawParams: {
        money: 0,
        verifyCode: '',
        payeeAccount: '',
        payeeName: ''
      },
      cooldown: 0,
      balance: 0,
      walletFlowDetailList: [],
      wallet: {},
      hasNext: true,
      searchParam: Object.assign({}, DEFAULT_SEARCH_PARAM),
      openWithdraw: false
    }
  },
  created () {
    this.params = queryParser(weex.config.bundleUrl)
    this.$watch('withdrawParams', () => {
      this.validateOk = this.validate()
    }, {deep: true})
    Deferred.when(this.loadData(), this.search()).always(() => {})
  },
  methods: {
    loadData () {
      api.page.myBalance.data(this.searchParam).done(rs => {
        let wallet = rs.data.wallet
        this.money = wallet.money.toFixed(2)
        this.wallet = wallet
        this.openWithdraw = rs.data.openWithdraw
        this.withdrawParams.payeeAccount = rs.data.payeeAccount
        this.withdrawParams.payeeName = rs.data.payeeName
        wallet.money = wallet.money.toFixed(2)
        this.withdrawParams.money = parseInt(wallet.money)
        this.minWithdrawValue = rs.data.minWithdrawValue
        if (this.params.withdraw === '1') {
          this.params.withdraw = 0
          if (!this.openWithdraw) {
            modal.alert({message: '提现暂时关闭，请等待开放！'})
          } else {
            this.withdrawPanelShow = true
          }
        }
      })
    },
    withdrawPanelHidden () {
      this.withdrawPanelShow = false
    },
    onXRefresh (event) {
      this.searchParam.page = 1
      this.onRefresh(event, this.doRefresh())
    },
    doRefresh () {
      return Deferred.when(this.loadData(), this.search())
    },
    onLoadingMore (event) {
      this.loadingMore = true
      this.searchParam.page = this.searchParam.page + 1
      this.search(true, () => {
        this.loadingMore = false
      })
    },
    gotoTop () {
      let dom = weex.requireModule('dom')
      dom.scrollToElement(this.$refs.top)
    },
    onPageScroll (event) {
      this.onPageScrollForScrollTop(event)
    },
    rightItemClick () {
      if (!this.openWithdraw) {
        modal.alert({message: '提现暂时关闭，请等待开放！'})
        return
      }
      this.withdrawPanelShow = true
    },
    search (append, callback) {
      // if(this.loading) {
      //   return new Deferred().resolve()
      // }
      this.loading = true
      return api.walletFlowDetail.search(this.searchParam).done((rs) => {
        if (append) {
          this.walletFlowDetailList = this.walletFlowDetailList.concat(rs.data.results)
        } else {
          this.walletFlowDetailList = rs.data.results
        }
        let paging = rs.data
        this.hasNext = paging.hasNext
      }).always(() => {
        this.loading = false
        callback && callback()
      })
    },
    validate () {
      if (!this.withdrawParams.money) {
        return false
      }
      if (!this.withdrawParams.verifyCode ||
          this.withdrawParams.verifyCode.length !== 6) {
        return false
      }
      if (!this.withdrawParams.payeeAccount) {
        return false
      }
      if (!this.withdrawParams.payeeName) {
        return false
      }
      return true
    },
    applyWithdraw () {
      if (!this.validate() || this.withdrawDoing) {
        return
      }
      this.withdrawDoing = true
      this.loadingShow = true
      api.userWithdraw.withdraw(this.withdrawParams).done(rs => {
        if (rs.data) {
          modal.toast({message: '提现成功！', duration: 0.5})
          this.doRefresh()
          this.withdrawPanelShow = false
        } else {
        }
      }).always(rs => {
        this.withdrawDoing = false
        this.loadingShow = false
      })
    },
    sendMsg () {
      if (this.cooldown > 0) {
        return
      }
      if (this.minWithdrawValue > this.withdrawParams.money) {
        modal.toast({message: '提现金额不足，最低提现金额为' + this.minWithdrawValue + '元', duration: 1})
        return
      }
      api.sms.withdraw().done(rs => {
        let data = rs.data
        if (data.success) {
          this.cooldown = data.cooldown
          modal.alert({message: '短信验证码已发送到' + data.phone + '的手机上，请查收！'})
          this.cooldownCount()
        } else {
          if (data.cooldown) {
            this.cooldown = data.cooldown
            this.cooldownCount()
          } else {
            modal.alert({message: '短信验证码发送失败'})
          }
        }
      })
    },
    cooldownCount () {
      setTimeout(() => {
        this.cooldown--
        if (this.cooldown > 0) {
          this.cooldownCount()
        }
      }, 1000)
    },
    checkStatusStyle (flowDetail) {
      if (flowDetail.type === 'USER_WITHDRAW') {
        // 提现
        switch (flowDetail.status) {
          case 'WAIT_VERIFY' : return 'text-warning'
          case 'WAIT_TRANSFER' : return 'text-info'
          case 'TRANSFER_SUCCESS' : return 'text-success'
          case 'VERIFY_FAIL' : return 'text-danger'
        }
      }
    },
    showDetail (detail) {
      if (detail.type === 'USER_WITHDRAW') {
        navigator.push('user-withdraw.js?id=' + detail.relationId)
      }
    }
  }
}
</script>
